<?php

namespace app\admin\controller;

use app\admin\validate\SCategory as SCategoryValidate;
use app\common\business\SCategory as SCategoryBus;
use app\common\lib\Check;
use app\common\lib\toCamelCase;

class SCategory extends AuthBase
{
    //分类列表
    public function categoryList(){
        $where = [];
        $categoryName = $this->request->get('categoryName',"");
        $status = $this->request->get("status","");
        if($categoryName){
            $where[] = ['category_name', 'like', '%'.$categoryName.'%'];
        }
        if ($status !== null && $status !== '') {
            // 如果$status不为null且不为空字符串，则添加条件到$where数组
            $where[] = ["status", "=", $status];
        }
        $where[] = ["del_flag", "=", '0'];
        try {
            $menuData = (new SCategoryBus())->getNormalCategory($where,"*");
            $menuData = (new toCamelCase())->toCamelCaseArray($menuData);
            // 处理分类数据
            if (!empty($menuData)) {
                foreach ($menuData as &$item) {
                    // 拼接完整的图片URL
                    $item['categoryImg'] = (new Check())->checkUrl($item['categoryImg']);
                    $item['url'] = '/pages/category/category/index?id='.$item['categoryId'];
                    // 根据标志位设置类型名称
                    $typeName = [];
                    if ($item['isHome'] === 1) {
                        $typeName[] = '首页';
                    }
                    if ($item['isBest'] === 1) {
                        $typeName[] = '精品';
                    }
                    if ($item['isPoliteness'] === 1) {
                        $typeName[] = '有礼';
                    }
                    if ($item['isYouyi'] === 1) {
                        $typeName[] = '游恵';
                    }
                    $item['typeName'] = implode('/', $typeName);
                }
            }
        }catch (\Exception $e){
            $menuData = [];
        }
        return show(config("status.success"),"分类列表",$menuData);
    }

    //分类添加
    public function categoryAdd(){
        if (!$this->request->isPost()){
            return show(config("status.error"),"请求方式错误");
        }
        //参数校验
        $allParams = request()->param();
        $data = (new toCamelCase())->toCamelCaseArray($allParams,'1',2);
        $validate = new SCategoryValidate();
        if(!$validate->check($data)){
            return show(config("status.error"),$validate->getError());
        }
        try {
            if($data['type']){
                $flags = [
                    1 => 'is_home',
                    2 => 'is_best',
                    3 => 'is_politeness',
                    4 => 'is_youyi',
                ];

                foreach ($data['type'] as $item) {
                    if (isset($item) && array_key_exists($item, $flags)) {
                        $data[$flags[$item]] = 1;
                    }
                }
                $data['type'] = implode(',',$data['type']);
            }
            $result = (new SCategoryBus())->addCategory($data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"新增成功",$result);
    }

    //分类修改
    public function categoryEdit(){
        $allParams = request()->param();
        $data = (new toCamelCase)->toCamelCaseArray($allParams,1,2);
        try {
            // 假设checkUrl是一个静态方法，它返回需要检查的URL前缀（如"com/"）
            $urlPrefix = (new Check())->checkUrlPrefix();
            // 检查字符串是否以特定前缀开头
            if (strpos($data['category_img'], $urlPrefix) === 0) {
                // 直接使用前缀的长度来截取字符串
                $data['category_img'] = substr($data['category_img'], strlen($urlPrefix));
            }
            $data['is_home'] = $data['is_best'] = $data['is_politeness'] = $data['is_youyi'] = 0;
            if($data['type']){
                $flags = [
                    1 => 'is_home',
                    2 => 'is_best',
                    3 => 'is_politeness',
                    4 => 'is_youyi',
                ];

                foreach ($data['type'] as $item) {
                    if (isset($item) && array_key_exists($item, $flags)) {
                        $data[$flags[$item]] = 1;
                    }
                }
                $data['type'] = implode(',',$data['type']);
            }
            $result = (new SCategoryBus())->updateById($data['category_id'],$data);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"修改成功",$result);
    }

    //删除分类
    public function categoryDel(){
        $category = $this->request->param("category","","trim");
        if(empty($category)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $result = (new SCategoryBus())->DelCategoryIds($category);
        }catch (\Exception $e){
            return show(config('status.error'),$e->getMessage());
        }
        return show(config("status.success"),"删除成功",$result);
    }

    //分类详情
    public function categoryDetails(){
        $category = $this->request->param("category","","trim");
        if(empty($category)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $configData = (new SCategoryBus())->getCategoryById($category);
            $configData = (new toCamelCase())->toCamelCaseArray($configData);
            $configData['categoryImg'] = (new Check())->checkUrl($configData['categoryImg']);
            if($configData['type']){
                $configData['type'] = explode(',',$configData['type']);
                // 将数组中的每个元素从字符串转换为整数
                foreach ($configData['type'] as &$value) {
                    $value = (int)$value;
                }
                unset($value);
            }else{
                $configData['type'] = [];
            }
        }catch (\Exception $e){
            $configData = [];
        }
        return show(config("status.success"),"分类详情",$configData);
    }


    //查询分类下拉结构
    public function categoryTreeselect(){
        $categoryId = $this->request->param("categoryId","","trim");
        if($categoryId){
            $where[] = ["category_id", "<>", $categoryId];
        }
        $where[] = ["parent_id", "=", 0];
        $where[] = ["del_flag", "=", 0];
        $menuData = (new SCategoryBus())->categoryTree($where,'category_id,category_name');
        return show(config("status.success"),"ok",$menuData);
    }

    //上传文件
    public function categoryuploadFile(){
        $imgUrl = file::uploadFile('file','category');
        return show(config("status.success"),"ok",$imgUrl);
    }

    //分类无限极下拉结构
    public function categoryTree(){
        $where = [];
        $DeptData = (new SCategoryBus())->categoryTreeChildren($where);
        return show(config("status.success"),"ok",$DeptData);
    }

}
